<template>
  <div class="user">
    <!-- 面包蟹 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- input框 -->
    <div style="margin-top: 15px 0; ">
      <el-input
        v-model="query"
        @keyup.enter.native="search"
        placeholder="请输入内容"
        class="input-with-select"
        style="width:300px;"
      >
        <el-button @click="search" slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button @click="addDialogFormVisible=true" style="margin-left:20px" type="success">添加按钮</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="userList" highlight-current-row style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="200"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
      <el-table-column prop="mobile" label="用户电话"></el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="changeuser(scope.row.id,scope.row.mg_state)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="角色分配" placement="top">
            <el-button type="primary" icon="el-icon-share" @click="showGrandDialog(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="primary" icon="el-icon-delete" @click="deluserbyid(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :label-width="'80px'" ref="addForm" :rules="rules">
        <el-form-item label="名字" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button @click="addUserr" type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="grantdialogFormVisible">
      <el-form :model="grantForm" :label-width="'120px'">
        <el-form-item label="用户名">
          <el-input v-model="grantForm.username" auto-complete="off" disabled style="width:100px"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="grantForm.rid" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户的 -->
    <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
      <el-form :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="editUserSubimit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  getUserList,
  addUser,
  delUser,
  statusChange,
  grantUserRole,
  editUser
} from "@/api/axios.js";
import { getAllRoleLlist } from "@/api/roul-api.js";
// import { type } from 'os';
export default {
  data() {
    return {
      //  编辑的数据
      editdialogFormVisible: false,
      editForm: {
        username: "",
        email: "",
        mobile: "",
        id: ""
      },
     

      roleList: [],
      grantForm: {
        roleName: "",
        id: "",
        rid: ""
      },
      grantdialogFormVisible: false,
      // 设置默认的总页数为0
      total: 0,
      query: "",
      //当前页码数
      pagenum: 1,
      // 默认每页展示的记录数
      pagesize: 5,
      value2: true,
      userList: [],
      addDialogFormVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "564564@163.com",
        mobile: "13434344545"
      },
      //添加rules规则
      rules: {
        // 每个名字对应着一个规则
        // username: [
        //   // required：必须的
        //   // message：不满足规则时的提示信息
        //   // trigger：什么时候触发：blur指失去焦点时触发
        //   { required: true, message: '请输入用户名', trigger: 'blur' }
        // ],
        username: [
          { required: true, message: "请输入你的名字", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入你的密码", trigger: "blur" }
        ],
        email: [
          // wuhu0723@126.com
          //   学习正则就是学习它的元字符
          // 1.占位符，说明这个位置需要填入满足要求的字符
          // \w:合法字符： 0-9 a-z A-Z _   \W：非法字符
          // \d:数字：0-9   \D:非数字
          // 2.修饰符：修饰前面的字符所出现的次数，前面的字符默认是指前面的一个字符，除非你使用()包含
          // +：修饰前面的字符出现1次或多次
          // ？：修饰前面的字符出现0次或1次
          // {n,m}:修饰前面的字符最少出现n次，最多出现m次
          // {n}:修饰前面的字符出现n次
          // {n,}修饰前面的字符最少出现n次，最多没有限制
          {
            required: true,
            message: "请填写email",
            trigger: "blur",
            pattern: /\w+[@]\w+[.]\w{2,3}/
          }
        ],
        mobile: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          {
            pattern: /^1[345678]\d{9}$/,
            message: "请填写正确的手机号(11位数字)",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    // console.log(123);
    getUserList({
      query: this.query,
      pagenum: this.pagenum,
      pagesize: this.pagesize
    })
      .then(res => {
        // console.log(res);
        this.userList = res.data.data.users;
        this.total = res.data.data.total;
      })
      .catch(err => {
        console.log(err);
      });
    getAllRoleLlist().then(res => {
      // console.log(res)
      if (res.data.meta.status === 200) {
        this.roleList = res.data.data;
      }
    });
  },

  methods: {
    init() {
      getUserList({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      })
        .then(res => {
          // console.log(res);
          this.userList = res.data.data.users;
          this.total = res.data.data.total;
        })
        .catch(err => {
          console.log(err);
        });
    },
    addUserr() {
      // 1,再次实现数据的验证
      this.$refs.addForm.validate(valid => {
        console.log(123);
        if (valid) {
          addUser(this.addForm)
            .then(res => {
              if (res.data.meta.status === 201) {
                //  让对话框隐藏
                this.addDialogFormVisible = false;
                // 重置表单元素的数据
                this.$refs.addForm.resetFields();
                // 实现数据 刷新
                getUserList({
                  query: this.query,
                  pagenum: this.pagenum,
                  pagesize: this.pagesize
                })
                  .then(res => {
                    // console.log(res);
                    this.userList = res.data.data.users;
                    this.total = res.data.data.total;
                  })
                  .catch(err => {
                    console.log(err);
                  });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.meta.msg
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
      // 2 调用接口方法实现数据的添加
    },

    // 切换size下拉列表时触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.init();
    },
    //  切换到当前页触发
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.init();
    },
    search() {
      this.pagenum = 1;
      this.init();
    },

    // 删除用户的方法
    deluserbyid(id) {
      //  点击删除时获取提示
      //  alert('123')
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //如果点击确定就会执行删除
          delUser(id).then(res => {
            console.log(res);
            if (res.data.meta.status === 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.pagenum =
                Math.ceil(this.total - 1 / this.pagesize) <
                (this.pagenum ? --this.pagenum : this.pagenum);
              this.init();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    // 修改状态的方法
    changeuser(uid, type) {
      statusChange(uid, type).then(res => {
        console.log(res);
        if (res.data.meta.status === 200) {
          this.$message({
            type: "seccess",
            message: res.data.meta.msg
          });
        }
      });
    },

    // 分配角色
    // 1: 点击显示对话框
    showGrandDialog(row) {
      console.log(row);
      this.grantdialogFormVisible = true;
      this.grantForm.roleName = row.username;
      this.grantForm.id = row.id;
      this.grantForm.rid = row.rid;
    },
    grantRoleSubmit() {
      if (!this.grantForm.rid) {
        this.$message({
          type: "warning",
          message: "请先选择角色"
        });
        return false;
      }
      grantUserRole(this.grantForm.id, this.grantForm.rid).then(res => {
        console.log(res);
        if (res.data.meta.status === 200) {
          this.$message({
            type: "warning",
            message: res.data.meta.msg
          });
          this.grantdialogFormVisible = false;
        }
      });
    },
     //  点击编辑展示编辑界面
      showEditDialog(row) {
        // console.log(row);
        this.editdialogFormVisible = true,
        this.editForm.username = row.username;
        this.editForm.email = row.email;
        this.editForm.mobile = row.mobile;
        this.editForm.id = row.id;
      },
    editUserSubimit(){
      // 验证是否有这个数组进行编辑
    this.$refs.editForm.validate(valid=>{
        if(valid){
          // 如果就调用后台的数据
          // 这里是实参要得到整个editForm的数据
          console.log(this.editForm,"23222442")
          editUser(this.editForm)
          .then(res=>{
            console.log(res)
            if(res.data.meta.status===200){
              this.$message({
                type:'success',
                message: res.data.meta.msg
              })
             this.editdialogFormVisible=false
             this.init()
            }
          }).catch(err=>{
            if(err){
              this.$message({
                type:'warning',
                message:'用户名不合法'
              })
            }
          })
        }
      })
    }
  }
};
</script>



<style lang="less" scoped>
</style>
